<?php

$ch = curl_init();
$post_data = [
	'client_id' => '',
	'client_secret' => '',
	'grant_type' => 'silent',
	'kdt_id'     => '42511846'
];

$options = [
    CURLOPT_URL => 'https://open.youzan.com/oauth/token',
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_HEADER => ['Content-Type：application/x-www-form-urlencoded'],
    CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36",
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => $post_data,
];
curl_setopt_array($ch, $options);
$res = curl_exec($ch);
// $info = curl_getinfo($ch);
if ($res === FALSE) {
    print('curl Error: ' . curl_error($ch));
}

preg_match('/\{.*\}/',$res,$str);

$access_token = json_decode($str[0],true)['access_token'];

//请求收款二维码
$post = [
	'qr_name' => '这是测试',
	'qr_price'=> 0.5,
	'qr_type' => 'QR_TYPE_NOLIMIT'
];
$options[CURLOPT_URL] = 'https://open.youzan.com/api/oauthentry/youzan.pay.qrcode/3.0.0/create?access_token='.$access_token;
$options[CURLOPT_POSTFIELDS] = $post;
curl_setopt_array($ch,$options);
$res = curl_exec($ch);
preg_match('/\{.*\}/',$res,$str);
//var_dump($str);
$qr_code = json_decode($str[0],true)['response']['qr_code'];
$qr_id = json_decode($str[0],true)['response']['qr_id'];
// preg_match('/kdt_id=(.*)/', $qr_url,$client);

// $kdt_id = $client[1];

$client_id = $_POST['client_id'];



$qr_code = str_replace('\\', "", $qr_code);

try {

	$pdo = new PDO('mysql:host=localhost;dbname=shop','root','19960521');

					//echo "insert into pay (client_id,kdt_id) values ($client_id,$kdt_id)";

	$pm = $pdo -> exec('insert into pay (client_id,kdt_id) values ("'.$client_id.'",'.$qr_id.')');
	
	} catch (PDOException $e) {

		die ("Error!: " . $e->getMessage() . "<br/>");
}
echo $qr_code;
?>





